<?php

namespace App\Http\Controllers;

use App\Exceptions\ErpException;
use App\Http\Middleware\ErpMiddleware;
use App\Http\Requests\Order\Index\StoreRequest;
use App\Models\Express;
use App\Repositories\Order;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;


class DockingController extends Controller
{
    /**
     * @throws ErpException
     * @throws ValidationException
     */
    public function handle()
    {
        switch (ErpMiddleware::$type) {
            case 'order.create':
                return $this->handleOrderCreate();
            case 'order.cancel':
                return $this->handleOrderCancel();
            case 'order.stop':
                return $this->handleOrderStop();
            default:
                return $this->response('参数错误');
        }
    }

    /**
     * 仓库订单
     * @return \Illuminate\Http\JsonResponse
     * @throws ErpException
     * @throws ValidationException
     */
    private function handleOrderCreate()
    {
        $data = ErpMiddleware::$body;

        if(empty($data['express_code'])){
            throw new ErpException('express_code 必须填写！');
        }
        $express = Express::query()->where('code', '=', $data['express_code'])->first();
        if (is_null($express)) {
            throw new ErpException('快递不存在！');
        }

        $data['express_id'] = $express->getKey();
        $data['customer_id'] = ErpMiddleware::$customer->getKey();
        $data['areas'] = explode(" ", $data['areas']??'');
        $data['buyer_telephone'] = $data['buyer_telephone'] ?? $data['receiving_phone'];

        $validator = Validator::make($data, StoreRequest::rulesStatic());

        if ($validator->fails()) {
            throw new ValidationException($validator);
        }

        DB::transaction(function () use ($data) {
            /** @var Order $orderRepository */
            $orderRepository = app(Order::class);
            $orderRepository->createForApi(collect($data)->only([
                'number', 'customer_id', 'express_id', 'freight', 'buyer_name', 'receiving_name', 'receiving_phone', 'buyer_type', 'buyer_number', 'buyer_telephone', 'areas', 'address', 'remark', 'products', 'original_number', 'ebc_code', 'ebc_name', 'ebp_code', 'ebp_name',
            ])->toArray());
        });


        return $this->response('创建成功');
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    private function handleOrderCancel()
    {
        Log::error(ErpMiddleware::$body);
        DB::transaction(function () {
            /** @var Order $orderRepository */
            $orderRepository = app(Order::class);
            $orderRepository->cancelForApi(ErpMiddleware::$body);
        });

        return $this->response('拦截成功');
    }

}
